﻿using UnityEngine;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {
        [CtxMenuItem("Renderer/SubMesh/Combine/Clear",
            "Removes submeshes and any unused vertices from a mesh",
            ContextRequirements.SubMeshes, 0)]
        public static void RendererSubMeshClear()
        {
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<Renderer>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;
                if (!SkinnEx.HasMinimumRequirements(context)) return;
                SkinnContext.UndoRecord(context, "Clear SubMesh");

                var mesh = context.GetSharedMesh().Clone() as Mesh;
                mesh.subMeshCount = 1;
                mesh.SetTriangles(context.GetSharedMesh().triangles, 0);
                context.SetSharedMesh(mesh.GetSubmesh(0));
                var sharedMaterials = context.sharedMaterials;
                for (int i = 0; i < sharedMaterials.Length; i++)
                {
                    if (!sharedMaterials[i]) continue;
                    context.sharedMaterials = new Material[] { sharedMaterials[i] };
                    break;
                }

                SkinnEx.Release(mesh);
            }

            SkinnContext.Finished();
        }
    }
}